# -*- coding: utf-8 -*-
# @CreateTime: 2023/2/21 12:29
# @Author    : FangNan
# @File      : make_dict.py
# @Software  : PyCharm
# 做一个有趣的人Write_By_FangNan
# -*- coding: utf-8 -*-
# @CreateTime: 2022/6/21 20:29
# @Author    : FangNan
# @File      : make_dict_myself.py
# @Software  : PyCharm
# 做一个有趣的人Write_By_FangNan
import datetime
import json

from django.core import serializers
from django.core.paginator import Page
from django.db.models import QuerySet

def make_dict(data, is_safe=True):
    """
    做一个方法来解决django肝疼的序列化的问题
    :param data:
    :param is_safe: 如果不设为安全，可能会返回一些敏感字段，如private_key
    :return:
    """
    if data is None:
        return None
    if type(data) is Page:
        raise Exception("不再支持该种翻页方式,请修改成下标获取")
    elif type(data) is list:
        data_list = []
        for data_now in data:
            data_list.append(make_dict(data_now))
        return data_list
    elif type(data) is QuerySet:
        datas = json.loads(serializers.serialize("json", data))
        data_list = []
        for data in datas:
            fields_data = {}
            fields_data['id'] = data['pk']
            fields_data.update(data['fields'])
            for key in fields_data:
                fields_data[key] = data_clear(fields_data[key])
            if is_safe:
                if 'private_key' in fields_data:
                    fields_data.pop('private_key')
            data_list.append(fields_data)
        return data_list
    elif type(data) is dict or type(data) is list:
        return data
    else:
        data_now = data.__dict__
        if '_state' in data_now.keys():
            data_now.pop("_state")
        for key in data_now:
            data_now[key] = data_clear(data_now[key])
        if is_safe:
            if 'private_key' in data_now:
                data_now.pop('private_key')
        return data_now


# 清理逐个字段(django序列化回来的东西千奇百怪，尤其是日期)
def data_clear(input_str):
    # 2022-08-08T13:09:00.749Z
    if type(input_str) is str and len(input_str) == len("2022-07-30T02:28:56.587Z"):
        try:
            # 尝试转为datetime格式
            input_str = datetime.datetime.strptime(input_str, '%Y-%m-%dT%H:%M:%S.%fZ')
            return int(input_str.timestamp())
        except:
            pass

    if type(input_str) is str and len(input_str) == len("2022-07-29T06:52:08Z"):
        try:
            # 尝试转为datetime格式
            input_str = datetime.datetime.strptime(input_str, '%Y-%m-%dT%H:%M:%SZ')
            return int(input_str.timestamp())
        except:
            pass
    if type(input_str) is str and len(input_str) == len("2022-07-30T02:28:56.024"):
        try:
            # 尝试转为datetime格式
            input_str = datetime.datetime.strptime(input_str, '%Y-%m-%dT%H:%M:%S.%f')
            return int(input_str.timestamp())
        except:
            pass
    if type(input_str) is type(datetime.datetime.now()):
        return int(input_str.timestamp())
    return input_str

